﻿using System;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress10;
using Movements.DataSet;

namespace Movements.Controls
{
    public partial class MovementListUserControl : XtraUserControl, IGridView, IList
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.MovementSaved += delegate { SetGridDataSource(); };
                _controller.TargetEntitySaved += delegate { SetupTargetEntitiesLookupData(); };
                _controller.SupplierSaved += delegate { SetupSupplierLookupData(); };
                _controller.ProductSaved += delegate { SetupProductLookupData(); };
                SetGridDataSource();
            }
        }

        #endregion

        public MovementListUserControl()
        {
            InitializeComponent();
            gridView.OptionsView.ShowFooter = true;
            DevExpressHelper.SetColumnAsNumericAndPaint(colQuantidadeEntrada);
            DevExpressHelper.SetColumnAsNumericAndPaint(colQuantidadeSaida);
            DevExpressHelper.ShowGroupSummaryAsNumeric(gridView);
            gridView.DoubleClick += GridViewDoubleClick;
            gridView.CustomUnboundColumnData += GridViewCustomUnboundColumnData;
        }
        
        #region Private Methods

        private void SetupMovementTypeLookupData()
        {
            tipoMovimentoDataSet = _controller.GetMovementTypes();
            typeRepositoryItemLookUpEdit.Columns.Clear();
            typeRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Tipo", "Tipo", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            typeRepositoryItemLookUpEdit.DisplayMember = tipoMovimentoDataSet.TipoMovimento.NomeColumn.ColumnName;
            typeRepositoryItemLookUpEdit.ValueMember = tipoMovimentoDataSet.TipoMovimento.TipoColumn.ColumnName;
            typeRepositoryItemLookUpEdit.DataSource = tipoMovimentoDataSet.TipoMovimento;
        }

        private void SetupProductLookupData()
        {
            produtoDataSet = _controller.GetProducts();
            //
            productReferenceRepositoryItemLookUpEdit.Columns.Clear();
            productReferenceRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Referencia", "Referencia", 85, FormatType.None, "", true, HorzAlignment.Near)});
            productReferenceRepositoryItemLookUpEdit.DisplayMember = produtoDataSet.Produto.ReferenciaColumn.ColumnName;
            productReferenceRepositoryItemLookUpEdit.ValueMember = produtoDataSet.Produto.IdColumn.ColumnName;
            productReferenceRepositoryItemLookUpEdit.DataSource = produtoDataSet.Produto;
            //
            productDescriptionRepositoryItemLookUpEdit.Columns.Clear();
            productDescriptionRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Designacao", "Designacao", 85, FormatType.None, "", true, HorzAlignment.Near)});
            productDescriptionRepositoryItemLookUpEdit.DisplayMember = produtoDataSet.Produto.DesignacaoColumn.ColumnName;
            productDescriptionRepositoryItemLookUpEdit.ValueMember = produtoDataSet.Produto.IdColumn.ColumnName;
            productDescriptionRepositoryItemLookUpEdit.DataSource = produtoDataSet.Produto;
        }

        private void SetupSupplierLookupData()
        {
            fornecedorDataSet = _controller.GetSuppliers();
            supplierRepositoryItemLookUpEdit.Columns.Clear();
            supplierRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            supplierRepositoryItemLookUpEdit.DisplayMember = fornecedorDataSet.Fornecedor.NomeColumn.ColumnName;
            supplierRepositoryItemLookUpEdit.ValueMember = fornecedorDataSet.Fornecedor.IdColumn.ColumnName;
            supplierRepositoryItemLookUpEdit.DataSource = fornecedorDataSet.Fornecedor;            
        }

        private void SetupUserLookupData()
        {
            utilizadorDataSet = _controller.GetUsers();
            userRepositoryItemLookUpEdit.Columns.Clear();
            userRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            userRepositoryItemLookUpEdit.DisplayMember = utilizadorDataSet.Utilizador.NomeColumn.ColumnName;
            userRepositoryItemLookUpEdit.ValueMember = utilizadorDataSet.Utilizador.IdColumn.ColumnName;
            userRepositoryItemLookUpEdit.DataSource = utilizadorDataSet.Utilizador;
        }

        private void SetupTargetEntitiesLookupData()
        {
            equipamentoDestinoDataSet = _controller.GetTargetEntities();
            targetEquipmentRepositoryItemLookUpEdit.Columns.Clear();
            targetEquipmentRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            targetEquipmentRepositoryItemLookUpEdit.DisplayMember = equipamentoDestinoDataSet.EntidadeDestino.NomeColumn.ColumnName;
            targetEquipmentRepositoryItemLookUpEdit.ValueMember = equipamentoDestinoDataSet.EntidadeDestino.IdColumn.ColumnName;
            targetEquipmentRepositoryItemLookUpEdit.DataSource = equipamentoDestinoDataSet.EntidadeDestino;
        }

        private void SetGridDataSource()
        {
            var dataSet = _controller.GetMovements();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Movimento.TableName;
            SetupMovementTypeLookupData();
            SetupProductLookupData();
            SetupSupplierLookupData();
            SetupUserLookupData();
            SetupTargetEntitiesLookupData();
        }

        private void ShowMovement(long documentId)
        {
            var window = new MovementXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion

        public void AddDocument()
        {
            ShowMovement(-1);
        }

        public void DeleteDocument()
        {
            throw new NotImplementedException();
        }

        #region IGridView

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "MovementListUserControl"; }
        }

        #endregion

        public long? SelectedMovementId
        {
            get
            {
                if (gridView.SelectedRowsCount == 0)
                    return null;
                if(gridView.GetSelectedRows()[0] < 0)
                    return null;
                return ((MovimentosDataSet.MovimentoRow)gridView.GetDataRow(gridView.GetSelectedRows()[0])).Id;
            }
        }

        void GridViewCustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            var movement = (MovimentosDataSet.MovimentoRow)gridView.GetDataRow(e.RowHandle);
            if (movement == null)
                return;
            if (e.Column == colFornecedorReferencia)
            {
                var productSupplier = produtoDataSet.Fornecedor.FindByIdProdutoIdFornecedor(movement.IdProduto, movement.IdFornecedor);
                e.Value = productSupplier.IsReferenciaFornecedorNull() ? "" : productSupplier.ReferenciaFornecedor;
            }
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var movement = (MovimentosDataSet.MovimentoRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (movement == null)
                return;
            ShowMovement(movement.Id);
        }

    }
}
